package db.day04;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * @Author Gan
 * @Date 2021/5/26 14:05
 * @Description: 自己实现一个数据库连接池，遵循规范
 * 初始容量
 */
public class MyConnectionPool {
    //自定义一个数据库连接池，底层是链表
    private static LinkedList<Connection> linkedList;
    //需要扩容的最小临界点
    static int MIN_CAPACITY = 3;
    //每次扩容的增量
    static int INCREMENT = 5;
    //初始容量是10
    static int INIT_CAPACITY = 10;

    static {
        linkedList = new LinkedList<>();
        addCapacity(INIT_CAPACITY);

    }

    public static void addCapacity(int size) {
        for (int i = 0; i < size; i++) {
            Connection connection = JDBCUtils.getConnection();
            linkedList.addFirst(connection);
        }
    }

    //获得连接
    public static Connection getConnection() {
        //连接池到了最小临界值则扩容，参数验证
        if (linkedList.size() <= MIN_CAPACITY) {
            addCapacity(INCREMENT);
        }
        //否则给返回一个连接资源
        return linkedList.removeLast();
    }

    //返回连接
    public static void returnConnection(Connection connection) {
        linkedList.addFirst(connection);
    }

}
